import { constantRoutes } from '@/router'
import { getMenu } from '@/api/user'
console.log(process.env.NODE_ENV)
const _import = require('@/router/_import_' + process.env.NODE_ENV)

/* 设置路由组件 */
function getRouterComponent (routes) {
  routes.forEach(item => {
    item.component = _import(item.component)
    if (item.children && item.children.length > 0) {
      getRouterComponent(item.children)
    } else {
      delete item.redirect
      delete item.children
    }
  })
  return routes
}

const permission = {
  state: {
    routers: constantRoutes
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.routers = constantRoutes.concat(routers)
    }
  },
  actions: {
    GenerateRoutes ({ commit }) {
      return new Promise((resolve, reject) => {
        getMenu({}).then(response => {
          let accessedRouters = response.object
          accessedRouters = getRouterComponent(accessedRouters)
          commit('SET_ROUTERS', accessedRouters)
          resolve(accessedRouters)
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default permission
